﻿using AutoMapper;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories.RepositoryEntityFrameworkCore.Sys;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application.RoleApp
{
    [AutoDi()]
    public class SysRoleAppService : BaseAppService<SysRoleDto, SysRole, SysRoleRepository>
    {
        public SysRoleAppService(SysRoleRepository repository) : base(repository)
        {
        }

        public virtual async Task<IPageModel<SysRoleDto>> GetListAsync(PagingModel<SysRoleDto> pagingQueryModel)
        {
            IPageModel<SysRoleDto> result;
            var where = this.CreateQRList()
                .Add(nameof(SysRoleDto.Name), "in")
                .Add(nameof(SysRoleDto.CreateFactory), "=");

            var lpom = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            lpom.QueryWhere = where;
            result = await LoadPageOffsetAsync(lpom);
            return result;
        }

        /// <summary>
        /// 根据角色获取权限
        /// </summary>
        /// <returns></returns>
        public async Task<List<Guid>> GetMenuListByRoleAsync(Guid roleId)
        {
            return await _repository.GetMenuListByRoleAsync(roleId);
        }

        /// <summary>
        /// 更新角色权限关联关系
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="roleMenus">角色权限集合</param>
        /// <returns></returns>
        public async Task<bool> UpdateRoleMenuAsync(Guid roleId, List<SysRoleMenuDto> roleMenus)
        {
            return await _repository.UpdateRoleMenuAsync(roleId, Mapper.Map<List<SysRoleMenu>>(roleMenus));
        }

        public async Task<IEnumerable<object>> GetRoleListAsync(Guid? factoryId)
        {
            var factoryRoleList = await base.GetListAsync(null, null, null, _repository.QueryBase().Where(a => a.CreateFactory == factoryId), null);
            var roleList = factoryRoleList.Select(role => (new { label = role.Name, key = role.Id.ToString() }));
            return roleList;
        }


    }
}
